package middleware

import (
	"lan-file-transfer/core"
	"lan-file-transfer/models"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头或查询参数获取token
		token := c.GetHeader("Authorization")
		if token == "" {
			token = c.Query("token")
		}

		if token == "" {
			c.JSON(http.StatusUnauthorized, models.ErrorResponse("未提供认证令牌"))
			c.Abort()
			return
		}

		// 移除 "Bearer " 前缀
		token = strings.TrimPrefix(token, "Bearer ")

		// 验证token
		claims, err := core.ValidateToken(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, models.ErrorResponse("无效的认证令牌"))
			c.Abort()
			return
		}

		// 将客户端IP存入上下文
		c.Set("client_ip", claims.ClientIP)
		c.Next()
	}
}
